/**
 * copyright(c) 2013 www.jiongshibaoliao.com, All Rights Reserved.
 * project: jiongshibaoliao 
 * author: 曾帅
 * date: 2014-1-25 下午01:44:43
 * version: v1.0
 */

package com.jiongshibaoliao.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * @project jiongshibaoliao
 * @author 曾帅
 * @version 1.0
 * @date 2014-1-25 下午01:44:43
 */

public class WaterMark {
	
	private static final Logger logger = Logger.getLogger(WaterMark.class);
	
	public final static void pressImage(String pressImg, String targetImg) {
		WaterMark.pressImage(pressImg, targetImg, 0, 0);
	}

	public final static void pressImage(String waterMarkImg, String targetImg, int x, int y) {
		try {
			File targetFile = new File(targetImg);
			Image targetSrc = ImageIO.read(targetFile);
			int width = targetSrc.getWidth(null);
			int height = targetSrc.getHeight(null);
			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics graphics = image.createGraphics();
			graphics.drawImage(targetSrc, 0, 0, width, height, null);

			File waterMarkFile = new File(waterMarkImg);
			Image waterMarkSrc = ImageIO.read(waterMarkFile);
			int waterMarkWidth = waterMarkSrc.getWidth(null);
			int waterMarkHeight = waterMarkSrc.getHeight(null);
			graphics.drawImage(waterMarkSrc, width - waterMarkWidth - x, height - waterMarkHeight - y, waterMarkWidth, waterMarkHeight, null);
			graphics.dispose();
			FileOutputStream out = new FileOutputStream(targetImg);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(image);
			out.close();
		} catch (Exception e) {
			logger.error("添加水印失败- 图片水印：", e);
		}
	}

	public static void pressText(String pressText, String targetImg, String fontName, int fontStyle, int fontSize, int x, int y) {
		try {
			File targetFile = new File(targetImg);
			Image targetSrc = ImageIO.read(targetFile);
			int width = targetSrc.getWidth(null);
			int height = targetSrc.getHeight(null);
			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics graphics = image.createGraphics();
			graphics.drawImage(targetSrc, 0, 0, width, height, null);
			graphics.setColor(Color.RED);
			graphics.setFont(new Font(fontName, fontStyle, fontSize));

			graphics.drawString(pressText, width - fontSize - x, height - fontSize / 2 - y);
			graphics.dispose();
			FileOutputStream out = new FileOutputStream(targetImg);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(image);
			out.close();
		} catch (Exception e) {
			logger.error("添加水印失败- 文字水印：", e);
		}
	}
}
